#import "EGORefreshTableFooterView.h"

//#define  RefreshViewHight 45.0f
#define  RefreshViewHight 5.0f

#define TEXT_COLOR       [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f


@interface EGORefreshTableFooterView (Private)
- (void)setState:(EGOFooterPullRefreshState)aState;
@end

@implementation EGORefreshTableFooterView

@synthesize delegate=_delegate;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, self.frame.size.height - 40.0f - 15.0f, self.frame.size.width, 20.0f)];
        label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        label.font = [UIFont systemFontOfSize:12.0f];
        label.textColor = TEXT_COLOR;
        label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
        label.shadowOffset = CGSizeMake(0.0f, 1.0f);
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = UITextAlignmentCenter;
        [self addSubview:label];
        _lastUpdatedLabel=label;
        _lastUpdatedLabel.hidden = YES;
        [label release];
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, self.frame.size.height - 20.0f - 10.0f, self.frame.size.width, 20.0f)];
        label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        label.font = [UIFont boldSystemFontOfSize:13.0f];
        label.textColor = TEXT_COLOR;
        label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
        label.shadowOffset = CGSizeMake(0.0f, 1.0f);
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = UITextAlignmentCenter;
        [self addSubview:label];
        _statusLabel=label;
        _statusLabel.transform = CGAffineTransformMakeRotation(270 * M_PI / 180.0);
        [label release];
        
        self.transform = CGAffineTransformMakeRotation(-M_PI);
        [self setState:EGOFOOTERPullRefreshNormal];
    }
    return self;
}

#pragma mark -
#pragma mark Setters

- (void)refreshLastUpdatedDate {
    if ([_delegate respondsToSelector:@selector(egoRefreshTableFooterDataSourceLastUpdated:)]) {
		NSDate *date = [_delegate egoRefreshTableFooterDataSourceLastUpdated:self];
		[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault];
		NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
		[dateFormatter setDateStyle:NSDateFormatterShortStyle];
		[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        _lastUpdatedLabel.text = [NSString stringWithFormat:@"上次更新: %@", [dateFormatter stringFromDate:date]];
		[[NSUserDefaults standardUserDefaults] setObject:_lastUpdatedLabel.text forKey:@"EGORefreshTableView_LastRefresh"];
		[[NSUserDefaults standardUserDefaults] synchronize];
    } else {
        _lastUpdatedLabel.text = nil;
    }
}

- (void)setState:(EGOFooterPullRefreshState)aState{
    switch (aState) {
        case EGOFOOTERPullRefreshPulling:
        {
            _statusLabel.text = NSLocalizedString(@"制冷", @"Release");
        }
            break;
        case EGOFOOTERPullRefreshNormal:
        {
            _statusLabel.text = NSLocalizedString(@"之前", @"Keep Going");
//            [_indicator stopAnimating];
            [self refreshLastUpdatedDate];
        }
            break;
        case EGOFOOTERPullRefreshLoading:
        {
            _statusLabel.text = NSLocalizedString(@"制冷中", @"It is a ...");
        }
            break;
        default:
            break;
    }
    
    _state = aState;
}

#pragma mark -
#pragma mark ScrollView Methods

//手指屏幕上不断拖动调用此方法
- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView {
//    Log(@"MARK %f %f",scrollView.contentSize.height, scrollView.contentOffset.y);
    if (_state == EGOFOOTERPullRefreshLoading) {
        CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
        offset = MIN(offset, 60);
        scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0f, RefreshViewHight, 0.0f);
    } else if (scrollView.isDragging) {
        BOOL _loading = NO;
        if ( scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height - 40 ) {
            //            Log(@"MARK %d %f",tmpR, scrollView.contentOffset.y);
            int tmpR = 8 - ((int)(abs(scrollView.contentOffset.y)/4)%8);
            if( tmpR != rolling){
                rolling = tmpR;
                //            Log(@"MARK %d %f",tmpR, scrollView.contentOffset.y);
                [_delegate egoRefreshTableFooterDidStart:self :rolling];
            }
		}else if( scrollView.contentOffset.y > 0 ){
            [_delegate egoRefreshTableFooterDidStop:self];
        }
        
        if ([_delegate respondsToSelector:@selector(egoRefreshTableFooterDataSourceIsLoading:)]) {
            _loading = [_delegate egoRefreshTableFooterDataSourceIsLoading:self];
        }
        if (_state == EGOFOOTERPullRefreshPulling && scrollView.contentOffset.y + (scrollView.frame.size.height) < scrollView.contentSize.height + RefreshViewHight && scrollView.contentOffset.y > 0.0f && !_loading) {
            [self setState:EGOFOOTERPullRefreshNormal];
        } else if (_state == EGOFOOTERPullRefreshNormal && scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height + RefreshViewHight && !_loading) {
            [self setState:EGOFOOTERPullRefreshPulling];
        }
        if (scrollView.contentInset.bottom != 0) {
            scrollView.contentInset = UIEdgeInsetsZero;
        }
    } else {
        [_delegate egoRefreshTableFooterDidStop:self];
    }
}

//当用户停止拖动，并且手指从屏幕中拿开的的时候调用此方法
- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView {
    BOOL _loading = NO;
    if ([_delegate respondsToSelector:@selector(egoRefreshTableFooterDataSourceIsLoading:)]) {
        _loading = [_delegate egoRefreshTableFooterDataSourceIsLoading:self];
    }
    if (scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height + RefreshViewHight && !_loading) {
        if ([_delegate respondsToSelector:@selector(egoRefreshTableFooterDidTriggerRefresh:)]) {
            [_delegate egoRefreshTableFooterDidTriggerRefresh:self];
        }
        [self setState:EGOFOOTERPullRefreshLoading];
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.2];
        scrollView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, RefreshViewHight, 0.0f);
        [UIView commitAnimations];
    }
}

//当开发者页面页面刷新完毕调用此方法，[delegate egoRefreshScrollViewDataSourceDidFinishedLoading: scrollView];
- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:.3];
    [scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
    [UIView commitAnimations];
    [self setState:EGOFOOTERPullRefreshNormal];
}

#pragma mark -
#pragma mark Dealloc

- (void)dealloc {
    _delegate=nil;
    _statusLabel = nil;
    _lastUpdatedLabel = nil;
    [super dealloc];
}

@end
